#pragma once 

#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
using namespace std;

//设计方的视角

template<class T>
using func_t = function<void(T)>;  //返回值为void, 参数为T的类型

template<class T>
class Thread
{
public:
    Thread(const string& threadname, func_t<T> func, T data)
        :_tid(0)
        ,_threadname(threadname)
        ,_isrunning(false)
        ,_func(func)
        ,_data(data)
    {}

    //改为static, 参数就没有this指针了!
    static void* ThreadRoutine(void* args) //不加static, 类内方法, 默认携带this指针
    {
        Thread* ts = static_cast<Thread *>(args);
        ts->_func(ts->_data);
        return nullptr;   
    }

    bool start()
    {
        int n = pthread_create(&_tid, nullptr, ThreadRoutine, this);
        if(n == 0) 
        {
            _isrunning  = true;
            return true;
        }
        else 
        {
            return false;
        }
    }

    bool join()
    {
        if(!_isrunning) return true;
        int n = pthread_join(_tid, nullptr);
        if(n == 0)
        {
            _isrunning = false;
            return true;
        }
        else
        {
            return false;
        }
    }

    string ThreadName()
    {
        return _threadname;
    }
    
    bool IsRunning()
    {
        return _isrunning;
    }

    ~Thread()
    {}

    
private:
    pthread_t _tid;
    string  _threadname;
    bool _isrunning;
    func_t<T> _func; //回调函数
    T _data;
};